using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using ContentOverContainer.SimpleSyntax;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;
using Roslyn.Compilers.Common;
using Roslyn.Services;
using Roslyn.Services.FindReferences;
using System.IO;
using System.Reflection;

namespace ContentOverContainer
{

    /// <summary>
    /// http://social.msdn.microsoft.com/forums/en-us/roslyn
    /// the goal is to use the MultiplicityRewriter to
    /// 1. find all definitions of the MultiplicityAttribute
    /// 2. build a list with all references of the MultiplicityAttribute annotated notes
    /// 3. build a list of org nodes and new nodes with changed Type to the appropriate Multiplicity-Kind
    /// later on
    /// 4. processes references list and add to list of org and new (changed) nodes
    /// 5. resolve dependencies between note to be replaced
    /// 6. replace all nodes in org-new list on tree
    /// <author>Harald Binkle</author>
    /// </summary>
    class Program
    {
        private static bool m_TargetIsSolution ;
        /// <summary>
        /// Mains the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <author>Harald Binkle</author>
        /// <exception cref="System.ArgumentException">The code to process already contains syntax errors:  + errors</exception>
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Please specify a solution or project file.");
                return;
            }

            var path = args[0];
            if (!File.Exists(path))
                Console.WriteLine("The specified file '{0}' does not exist.",path);

            if (!Path.IsPathRooted(path))
                path = Path.Combine(Environment.CurrentDirectory, path);           


            ISolution orgSolution = null;
            if (path.EndsWith(".csproj"))
            {
                try
                {
                    orgSolution = Solution.LoadStandAloneProject(path).Solution;
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to load the project:" + Environment.NewLine + e.ToString());
                    if (Debugger.IsAttached)
                        Console.ReadLine();
                }
            }
            else
            {
                if (path.EndsWith(".sln"))
                {
                    m_TargetIsSolution = true;
                    try
                    {
                        orgSolution = Solution.Load(path);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to load the solution:" + Environment.NewLine + e.ToString());
                    }
                }
                else Console.WriteLine("The specified file is no c# project or solution.");
            }

            if (orgSolution == null)//invalid commandline parameter
                return;       

            //rewrite code
            var newSolution = MultiplicityConverter.Convert(orgSolution);
            var solutionOrProjectDir = Path.GetDirectoryName(path);
            var destDir = Path.Combine(Environment.CurrentDirectory,"Converted\\");

            var newSolutionPath = BuildNewPath(solutionOrProjectDir, destDir, path);
            if (Directory.Exists(destDir))
                Directory.Delete(destDir, true);
            Directory.CreateDirectory(destDir);
            Thread.Sleep(100);//give it some time to create the directory
            if (!Directory.Exists(destDir))
                throw new DirectoryNotFoundException("Failed to create directory: " + destDir);
            if(m_TargetIsSolution)
                File.Copy(path, newSolutionPath);

            foreach (var project in newSolution.Projects)
            {
                //copy project file to destdir
                var newProjectPath = BuildNewPath(solutionOrProjectDir, destDir, project.FilePath);
                if (newProjectPath.Contains("SRC."))
                    newProjectPath = newProjectPath.Replace("SRC.", ".");
                File.Copy(project.FilePath, newProjectPath);

                foreach (var document in project.Documents)
                {
                    if (document.Name.StartsWith(".NETFramework,Version"))//skip temporary project file generated by compiler
                        continue;
                                
                    var root = document.GetSyntaxRoot();

                    //log code
                    var strBuild = new StringBuilder();
                    var code = root.ToString();
                    var lines = code.Split('\n');
                    for (int i = 0; i < lines.Length; i++)
                    {
                        strBuild.AppendLine(String.Format("{0}  {1}", i, lines[i].TrimEnd()));
                    }


                    Console.WriteLine(strBuild.ToString());
                    var newDocPath = BuildNewPath(solutionOrProjectDir, destDir, document.FilePath);
                    Directory.CreateDirectory(Path.GetDirectoryName(newDocPath));
                    File.AppendAllText(newDocPath, code);
                    //LogBoth(strBuild.ToString());


                    //check adjusted code
                    var errors = CheckForCompileErrors((SyntaxTree)document.GetSyntaxTree());
                    if (!String.IsNullOrEmpty(errors))
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        var errorlines = errors.Split('\n');
                        var errorBuilder = new StringBuilder();
                        foreach (var line in errorlines)
                        {
                            errorBuilder.AppendLine("//" + line.TrimEnd());
                        }
                        LogBoth(errorBuilder.ToString(), newDocPath);
                    }


                    LogBoth( "//#################################", newDocPath);
                    Console.ForegroundColor = ConsoleColor.White;                    
                }               
            }

            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Done.");
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("\r\nPlease find your converted solution/project in:" +Environment.NewLine + destDir);
            Console.ForegroundColor = ConsoleColor.White;
#if DEBUG
            //Developer Test:
            var testFile = Path.Combine(destDir,"CodeToTest.cs");
            if (File.Exists(testFile) && Debugger.IsAttached)
            {
                var resultFile = Path.Combine(destDir, "Results.cs");
                File.Copy(testFile, resultFile);
                System.Diagnostics.Process.Start(resultFile);
            }
            #endif
        }

        private static string BuildNewPath(string solutionDir, string destDir, string filePath)
        {
            filePath = Path.GetFullPath((new Uri(filePath)).LocalPath);//make path absolute
            solutionDir = Path.GetFullPath((new Uri(solutionDir)).LocalPath);//make path absolute
            var result = filePath.Replace(solutionDir, destDir);
            result = result.Replace("\\\\", "\\");
            return result;
        }

        private static void LogBoth(string pText, string pFile)
        {
            Console.WriteLine(pText);
            File.AppendAllText(pFile, pText + Environment.NewLine);
        }

        public static string CheckForCompileErrors(SyntaxTree pTree)
        {
            Diagnostic[] dg = pTree.GetDiagnostics().ToArray();
            if (dg.Length > 0)
            {
                var error = new StringBuilder("The following compile error occured:" + Environment.NewLine);

                foreach (Diagnostic d in dg)
                    error.AppendLine("Info: " + d.ToString());
                return error.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

    }




}
